//
//  GRUMengCommon.m
//  YC_GRice
//
//  Created by LiuFeng on 2018/7/9.
//  Copyright © 2018年 YeCai. All rights reserved.
//

#import "GRUMengCommon.h"
#import <UMCommon/UMCommon.h>

#define platForms   @[@"微信", @"朋友圈",@"面对面分享"]
#define shareImages @[@"share_3", @"share_2",@"facecode"]

@interface GRUMengCommon ()

{
    UIViewController *_currentVc;
    NSString *_title;
    NSString *_content;
    NSString *_image;
    NSString *_url;
    NSDictionary *_option;
    BOOL _isMini;
    
    CGFloat sH;
}

@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) NSMutableArray *platforms;
@property (nonatomic, strong) NSArray *animationTimes;
@property(nonatomic,copy)ShowCodeBlock  codeBlock;

@end


@implementation GRUMengCommon


+ (instancetype)shareUMeng {
    static GRUMengCommon *umeng = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        umeng = [[GRUMengCommon alloc] init];
    });
    
    return umeng;
}


+ (void)UMeng {
    
    [UMConfigure initWithAppkey:UMENGKEY channel:nil];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WECHATKEY appSecret:WECHATSECRET redirectURL:@"http://mobile.umeng.com/social"];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:WECHATKEY appSecret:WECHATSECRET redirectURL:@"http://mobile.umeng.com/social"];
    
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:@"" appSecret:@"" redirectURL:@"http://mobile.umeng.com/social"];
}




#pragma Mark ================== 分享界面 ====================

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self drawUI];
    }
    return self;
}


- (void)drawUI {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [window addSubview:self.backgroundView];
    [window bringSubviewToFront:_backgroundView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
    [self.backgroundView addGestureRecognizer:tap];
    
//    _animationTimes = [NSArray arrayWithObjects:@.3, @.5, @.7, @.9, nil];
//    _platforms      = [NSMutableArray array];
    
    sH = IS_IPHONEX ? 179 : 145;
    _coverView      = [[UIView alloc] initWithFrame:CGRectMake(0, KscreenHeight, KscreenWidth, sH)];
    _coverView.backgroundColor = [UIColor whiteColor];
    [window addSubview:_coverView];

    CGFloat ItemWith = 53;
    CGFloat ItemMargain = (KscreenWidth -10- (platForms.count *ItemWith))/(platForms.count+1);
    /*
    for (int i = 0; i < platForms.count; i++) {
        UIView *actionView = [[UIView alloc] initWithFrame:CGRectMake(i * itemWidth + i * 15, KscreenWidth, itemWidth, itemWidth + 20)];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, itemWidth, itemWidth);
        button.tag = 100 + i;
        [button setImage:[UIImage imageNamed:shareImages[i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(shareFriends:) forControlEvents:UIControlEventTouchUpInside];
        [actionView addSubview:button];
        
        UILabel *platLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, itemWidth, itemWidth, 20)];
        platLabel.textAlignment = NSTextAlignmentCenter;
        platLabel.font = [UIFont systemFontOfSize:14];
        platLabel.textColor = HEXCOLOR(0x999999);
        platLabel.text = platForms[i];
        [actionView addSubview:platLabel];
        
        [_backgroundView addSubview:actionView];
        
        [_platforms addObject:actionView];
    }
     */
    
    
    for (int i = 0; i < platForms.count; i++) {

        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(5+ ItemMargain *(i+1) +ItemWith*i, 17, ItemWith, ItemWith);
        NSLog(@"%lf",ItemMargain *(i+1) +ItemWith);
        button.tag = 100 + i;
        [button setImage:[UIImage imageNamed:shareImages[i]] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(shareFriends:) forControlEvents:UIControlEventTouchUpInside];
         [self.coverView addSubview:button];
        UILabel *platLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 77, 100,13)];
        platLabel.text = platForms[i];
        platLabel.font = [UIFont systemFontOfSize:14];
        platLabel.textColor = HEXCOLOR(0x666666);
        platLabel.textAlignment = NSTextAlignmentCenter;
        platLabel.centerX = button.centerX;

        [self.coverView addSubview:platLabel];
    }
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, KscreenWidth, 0.6)];
    line.backgroundColor = KGMBACKGROUND_COLOR;
    [self.coverView addSubview:line];
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(0, 101, KscreenWidth, 44);
    [closeBtn setTitle:@"取消" forState:UIControlStateNormal];
    [closeBtn setTitleColor:KGMBLACK_COLOR forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [self.coverView addSubview:closeBtn];
    
    self.coverView.hidden       = YES;
    self.backgroundView.hidden  = YES;
}


- (void)sharePlatform:(UIViewController *)currentVc title:(NSString *)title content:(NSString *)content image:(NSString *)image webURL:(NSString *)webUrl miniApp:(BOOL)miniapp option:(NSDictionary *)option {
    _currentVc = currentVc;
    _title     = title;
    _content   = content;
    _image     = image;
    _url       = webUrl;
    _isMini    = miniapp;
    _option    = option;
    
    [self show];
}

- (void)show{
    self.backgroundView.hidden  = NO;
    self.coverView.hidden       = NO;
    [UIView animateWithDuration:.4 animations:^{
        _backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        _coverView.y    = KscreenHeight-sH;
    }];
}

- (void)hide{
    [UIView animateWithDuration:0.4 animations:^{
        _backgroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        _coverView.y    = KscreenHeight;
    } completion:^(BOOL finished) {
        self.backgroundView.hidden  = YES;
        self.coverView.hidden       = YES;
    }];
}

/*
- (void)makeAnimation:(BOOL)showState{
    
    [UIView animateWithDuration:.5 animations:^{
        if (showState) {
            _titleLabel.y = KscreenHeight/2 - 60;
        }else{
            _titleLabel.y = -25;
        }
    }];
    
    
    for (int i = 0; i < platForms.count; i++) {
        double time = [_animationTimes[i] doubleValue];
        UIView *actionV = _platforms[i];
        [UIView animateWithDuration:time animations:^{
            if (showState) {
                actionV.y = KscreenHeight/2-10;
            }else{
                actionV.y = KscreenHeight;
            }
        } completion:^(BOOL finished) {
            if (!showState && (i == platForms.count - 1)) {
                _backgroundView.hidden = YES;
            }
        }];
    }
}
*/

- (void)shareFriends:(UIButton *)button{
    NSInteger shareType;
    UMSocialMessageObject *object = [UMSocialMessageObject messageObject];
    NSData *imageData = nil;
    if (_image != nil) {
        if ([_image hasPrefix:@"http"]) {
            imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_image]];
        }else{
            imageData = [NSData dataWithContentsOfFile:_image];
        }
    }
    
    if (_url == nil) {
        UMShareImageObject *imageObject = [[UMShareImageObject alloc] init];
        [imageObject setShareImage:imageData];
        object.shareObject = imageObject;
    }else{
        UMShareWebpageObject *webObject = [UMShareWebpageObject shareObjectWithTitle:_title descr:_content thumImage:imageData];
        webObject.webpageUrl = _url;
        object.shareObject = webObject;
    }
    
    switch (button.tag) {
        case 100:{
            if (_isMini) {
                UMShareMiniProgramObject *miniProgram = [UMShareMiniProgramObject shareObjectWithTitle:_title descr:_content thumImage:_image];
                miniProgram.webpageUrl = _option[@"webpageUrl"];
                miniProgram.userName = _option[@"userName"];
                miniProgram.path = _option[@"path"];
                object.shareObject = miniProgram;
            }
            shareType = 1;
            [self postShareWith:shareType content:object];
        }
            break;
        case 101:{
            if (_isMini && NSStringNotNULL(_option[@"poster"])) {
                UMShareImageObject *imageObject = [[UMShareImageObject alloc] init];
               imageObject.shareImage = _option[@"poster"];
                object.shareObject = imageObject;
            }
            shareType = 2;
            [self postShareWith:shareType content:object];
        }
            break;
        case 102:
            [self showCodeView];
            break;
        default:
            shareType = 0;
            break;
    }
    
    [self hide];
}

-(void)showCodeView{
    if (self.codeBlock != nil) {
        self.codeBlock();
    }
    
}

- (void)JumpSubroutine:(UIViewController *)currentVc userName:(NSString *)userName path:(NSString *)path {
    WXLaunchMiniProgramReq *miniProgram = [WXLaunchMiniProgramReq object];
    miniProgram.userName                = userName;
    miniProgram.path                    = path;
    miniProgram.miniProgramType         = WXMiniProgramTypeRelease;
    [WXApi sendReq:miniProgram];
}

- (void)postShareWith:(NSInteger)type content:(UMSocialMessageObject *)object{
        [GRHUD showProgress:@"分享中"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           [GRHUD dismissHUD];
    });
    [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
    [[UMSocialManager defaultManager] shareToPlatform:type messageObject:object currentViewController:_currentVc completion:^(id result, NSError *error) {
     
        if (!error) {
            NSLog(@"分享成功");
        }else {
            NSLog(@"分享失败：%@",error);
        }
    }];

 
}

-(void)sharePlatform:(UIViewController *)currentVc title:(NSString *)title content:(NSString *)content Image:(UIImage *)image{
     UMSocialMessageObject *object = [UMSocialMessageObject messageObject];
    UMShareImageObject *imageObject = [UMShareImageObject shareObjectWithTitle:title descr:content thumImage:image];
    [imageObject setShareImage:image];
    object.shareObject = imageObject;
    [self postShareWith:UMSocialPlatformType_WechatSession content:object];
    
    
}
- (void)sharePlatform:(UIViewController *)currentVc title:(NSString *)title content:(NSString *)content image:(NSString *)image webURL:(NSString *)webUrl miniApp:(BOOL)miniapp option:(NSDictionary *)option showComplection:(ShowCodeBlock)showBlock{
    self.codeBlock = showBlock;
    [self sharePlatform:currentVc title:title content:content image:image webURL:webUrl miniApp:miniapp option:option ];
}


- (void)enterAppletChat:(UIViewController *)currentVc {
    [self JumpSubroutine:currentVc userName:@"gh_88e7bdd48c24" path:@"pages/personal/customerpersonnel/customerpersonnel"];
}

@end
